
from infra.handler import BaseHandler
# from common.log import logInfo
from .chatroom_db import create_chatroom
from .chatroom_db import get_chatroom_by_activity
from .chatroom_db import get_chatroom_by_id
import json
class ChatRoomHandler(BaseHandler):
    async def get(self):
        """获取聊天室信息"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return

            # 获取查询参数
            activity_id = self.get_argument('activity_id', None)
            chatroom_id = self.get_argument('chatroom_id', None)

            if activity_id:
                # 根据活动ID获取聊天室
                success, result = await get_chatroom_by_activity(int(activity_id))
            elif chatroom_id:
                # 根据聊天室ID获取信息
                success, result = await get_chatroom_by_id(int(chatroom_id))
            else:
                self.write(json.dumps({
                    "code": 400,
                    "msg": "缺少必要参数"
                }))
                return

            if success:
                self.write(json.dumps({
                    "code": 200,
                    "msg": "查询成功",
                    "data": result
                }))
            else:
                self.write(json.dumps({
                    "code": 404,
                    "msg": "聊天室不存在"
                }))
        except Exception as e:
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))

    async def post(self):
        """创建聊天室"""
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return

            body = json.loads(self.request.body)
            
            # 检查必填字段
            if 'activity_id' not in body or 'member_list' not in body:
                self.write(json.dumps({
                    "code": 400,
                    "msg": "缺少必填字段"
                }))
                return

            success, result = await create_chatroom(
                activity_id=body['activity_id'],
                creator_id=user_id,
                member_list=body['member_list']
            )

            if success:
                self.write(json.dumps({
                    "code": 200,
                    "msg": "聊天室创建成功",
                    "data": {"group_id": result}
                }))
            else:
                self.write(json.dumps({
                    "code": 404,
                    "msg": f"创建失败: {result}"
                }))

        except json.JSONDecodeError:
            self.write(json.dumps({
                "code": 400,
                "msg": "请求体格式错误"
            }))
        except Exception as e:
            self.write(json.dumps({
                "code": 404,
                "msg": str(e)
            }))